// request.js
const baseUrl = 'https://fanshanjia.vvv6g.cn/api/';

export const request = (url, method = 'GET', data = {}, header = {}) => {
	return new Promise((resolve, reject) => {

		// 判断如果不是登录和获取验证码接口，则请求头添加token字段
		if (!['mm/telcode', 'agent/login'].includes(url)) {
			// 获取用户登录后的token
			const str = uni.getStorageSync('userinfo') || '';
			const userInfo = str.length ? JSON.parse(str) : {};
			const token = userInfo?.access_token;
			// const token = '574ED75207373D31AD386DE455443FE8';
			// 判断token是否为空，为空则跳转登录页面
			if (!token?.length) {
				return uni.reLaunch({
					url: '/pages/login/login'
				});
			}
			header['access_token'] = token;
		}
		header['device'] = 'mini';
		uni.request({
			url: baseUrl + url,
			method: method,
			data: data,
			header: header,
			success: res => {
				const {
					code,
					data,
					message
				} = res.data;
				if (code == 401) {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				} else if (code == 200) {
					resolve(res.data);
				} else {
					uni.showToast({
						title: message,
						icon: 'none'
					});
				}
			},
			fail: err => {
				uni.hideLoading()
				uni.showToast({
					title: err.errMsg,
					icon: 'none'
				});
				reject(err);
			}
		});
	});
};

//文件上传封装
export const uploadFile = (filePath, formData) => {
	return new Promise((resolve, reject) => {
		let header = {};
		const str = uni.getStorageSync('userinfo') || '';
		const userInfo = str.length ? JSON.parse(str) : {};
		const token = userInfo?.access_token;
		header['access_token'] = token;
		header['Content-Type'] = "multipart/form-data";
		uni.uploadFile({
			url: baseUrl + filePath, //仅为示例，非真实的接口地址
			filePath: formData,
			name: 'file',
			header: header,
			success: res => {
				const {
					code,
					data,
					message
				} = JSON.parse(res.data);
				if (code == 200) {
					resolve(JSON.parse(res.data));
				} else {
					uni.showToast({
						title: message,
						icon: 'none'
					});
				}
			},
			fail: err => {
				reject(err);
			}
		});
	});
};

// 不同请求方式的封装
export const formPost = (url, param = {}) => {
	return request(url, 'post', param?.buffer, {
		'Content-Type': param.contentType
	});
};

export const formGet = (url, param = {}) => {
	return request(url, 'get', param?.buffer, {
		'Content-Type': param.contentType
	});
};

export const get = (url, param) => {
	return request(url, 'get', param, {
		'Content-Type': 'application/json'
	});
};

export const post = (url, param) => {
	return request(url, 'post', param, {
		'Content-Type': 'application/json'
	});
};

export const put = (url, param) => {
	return request(url, 'post', param, {
		'Content-Type': 'application/json'
	});
};

export const delet = (url, param) => {
	return request(url, 'post', param, {
		'Content-Type': 'application/json'
	});
};